import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

/**
 * 表单提交和验证的钩子函数
 * @param {Object} defaultFormData - 默认表单数据
 * @param {Function} submitFn - 提交函数
 * @param {Object} options - 配置选项
 * @param {Boolean} options.resetAfterSubmit - 提交后是否重置表单
 * @param {Function} options.validateFn - 自定义验证函数
 * @returns {Object} 表单数据和方法
 */
export function useForm(defaultFormData = {}, submitFn, options = {}) {
  const {
    resetAfterSubmit = true,
    validateFn = null
  } = options

  // 表单数据
  const formData = reactive({ ...defaultFormData })
  
  // 表单引用
  const formRef = ref(null)
  
  // 提交加载状态
  const submitting = ref(false)
  
  // 重置表单
  const resetForm = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
    Object.assign(formData, defaultFormData)
  }
  
  // 验证表单
  const validateForm = async () => {
    if (!formRef.value) return true
    
    try {
      return await formRef.value.validate()
    } catch (error) {
      console.error('表单验证失败', error)
      return false
    }
  }
  
  // 自定义验证
  const customValidate = async () => {
    if (validateFn && typeof validateFn === 'function') {
      try {
        return await validateFn(formData)
      } catch (error) {
        console.error('自定义验证失败', error)
        ElMessage.error(error.message || '验证失败')
        return false
      }
    }
    return true
  }
  
  // 提交表单
  const submitForm = async (data = null) => {
    // 验证表单
    const isValid = await validateForm()
    if (!isValid) return false
    
    // 自定义验证
    const isCustomValid = await customValidate()
    if (!isCustomValid) return false
    
    try {
      submitting.value = true
      
      // 提交数据，优先使用传入的数据，否则使用表单数据
      const submitData = data || { ...formData }
      const result = await submitFn(submitData)
      
      // 提交成功后重置表单
      if (resetAfterSubmit) {
        resetForm()
      }
      
      return result
    } catch (error) {
      console.error('表单提交失败', error)
      ElMessage.error(error.message || '提交失败')
      throw error
    } finally {
      submitting.value = false
    }
  }
  
  // 更新表单数据
  const updateFormData = (data) => {
    Object.assign(formData, data)
  }
  
  // 设置表单字段值
  const setFieldValue = (field, value) => {
    formData[field] = value
  }
  
  // 获取表单字段值
  const getFieldValue = (field) => {
    return formData[field]
  }
  
  // 清除表单验证
  const clearValidate = (props) => {
    if (formRef.value) {
      formRef.value.clearValidate(props)
    }
  }
  
  // 验证表单字段
  const validateField = (props) => {
    if (formRef.value) {
      return formRef.value.validateField(props)
    }
    return Promise.resolve()
  }
  
  return {
    formData,
    formRef,
    submitting,
    resetForm,
    validateForm,
    submitForm,
    updateFormData,
    setFieldValue,
    getFieldValue,
    clearValidate,
    validateField
  }
}